-module(cloap_module_handler).
-export([init/2]).
-export([admin_app/0]).
-include("cloap_record.hrl").

init(Req, Opts) ->
    AppId = cowboy_req:binding(appid, Req),
    %% Script = cowboy_req:binding(script, Req),
    Files = string:join([binary_to_list(X) || X <- cowboy_req:path_info(Req)], "/"),
    Script = lists:nth(5, re:split(binary_to_list(cowboy_req:path(Req)), "/")),  %% the 5th is script type

    Req2 = parse(AppId, Script, Files, Req),
    {ok, Req2, Opts}.


parse(AppId, Script, File, Req) ->
    [App] = cloap_store:find(app, AppId),

    #{url := Url} = App#app.callback,
    case httpc:request(binary_to_list(iolist_to_binary([Url, <<"/cloap/app/">>, Script, <<"/">>, File]))) of
        {error, Reason} ->
            cowboy_req:reply(400, [], <<Reason/binary>>, Req);
        {ok, {_Status, _Headers, Body}} ->
            cowboy_req:reply(200, [
                                   {<<"content-type">>, <<"text/plain; charset=utf-8">>}
                                  ], Body, Req)
    end.



admin_app() ->
    #app{ appid = ?ADMIN }.
